import Api from '@/utils/api.js';
import CC from '@/utils/cc.js';
import LocalStorage from '@/utils/localStorage.js';

export default function({
  // content 说明文档
  // https://nuxtjs.org/docs/internals-glossary/context/
  app,
  store,
  route,
  params,
  query,
  env,
  isDev,
  isHMR,
  redirect,
  error,
  $config,
  $axios}) {

  $axios.interceptors.request.use(
    config => {
      // 字符类型
      config.headers['Content-Type'] = 'application/json;charset=utf-8'
      // 客户端
      config.headers['client'] = 'h5'
      // 补充空对象请求
      config.data = config.data || {}
      return config
    },
    error => {
      return Promise.reject({code: 500, message: "请求配置出错"})
    }
  )
  $axios.onRequest(config => {
  })

  $axios.interceptors.response.use(
    response => {
      // 自己服务器
      if(response.config.url.indexOf("/api_v1") == 0){
        //正式环境：解密
        if(process.env.NODE_ENV != 'development'){
          // 解密
          var decrypt = CC.decrypt(response.data)
          response.data = JSON.parse(decrypt)
        }

        // 获取协议内容
        const res = response.data
        switch(res.code){

          // 成功
          case 200:
            // 如果是注册登录接口，存储用户信息
            if(response.config.url === Api.USER_REGISTER || response.config.url === Api.USER_LOGIN){
              LocalStorage.setItem("USER_INFO", response.data.data)
              LocalStorage.setItem("token", response.data.data.token)
            }

            return Promise.resolve(res.data)
          
          // 用户token失效
          case 100:          
            // 清空存储  
            LocalStorage.clear()

            if (process.client) {
              // 用户登录
              location.replace('/userLogin?ref='+ window.location.href)
            }else{
              // 服务器重定向页面
              redirect(302, '/userLogin')
            }
            return Promise.reject({code: res.code, message: res.message})

          default:
            return Promise.reject({code: res.code, message: res.message})
        }
      }else{
        // 其他服务器（百度等）
        return Promise.resolve(response.data)
      }
    },
  
    error => {
      return Promise.reject({code: 404, message: "未请求到有效地址"})
    }
  )
}